%%----------------------------------------------------
%% @doc 处理HTTP请求，分发到指定的模块去处理
%%----------------------------------------------------
-module(gameweb_handle).

-export([
        parse_args/1
        ,do/4
    ]).


%% @doc 解析并提取参数列表
%% <div>
%% 针对OTP 17.5版本升级后的中文编码字符处理
%% </div>
parse_args(Qs) ->
    %% Ps = mochiweb_request:parse_post(Req),
    lists:map(fun({K, V}) ->
                K1 = iolist_to_binary(K),
                unicode:characters_to_list(K1),
                V1 = iolist_to_binary(V),
                unicode:characters_to_list(V1),
                {K1, V1}
        end, Qs).


%% @doc 处理具体的请求
-spec do(Label :: string(), Method :: 'GET' | 'POST', Req :: term(), HandleMod :: atom()) -> term().
do(Label, Method, Req, HandleMod) ->
    Qs = case Method of
        'GET' ->
            mochiweb_request:parse_qs(Req);
        'POST' ->
            mochiweb_request:parse_post(Req)
    end,
    Ip = mochiweb_request:get(peer, Req),
    case HandleMod:handle(Label, Method, Ip, Qs) of
        {ok, Reply} when is_list(Reply) ->
            gameweb_web:ok(Req, unicode:characters_to_binary(Reply));
        {ok, Reply} when is_bitstring(Reply) ->
            gameweb_web:ok(Req, Reply);
        error ->
            Req:not_found()
    end.


%%----------------------------------------------------
%% Internal API
%%----------------------------------------------------

